package mannA1.controller;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import mannA1.model.Edge;
import mannA1.model.Model;
import mannA1.view.A1GUI;
import mannA1.view.LinesCanvas;

/** A controller for creating edges*/
public class DrawEdgeController implements MouseListener
{
	Model model;
	A1GUI a1gui;
	LinesCanvas canvas;
	
	public DrawEdgeController (A1GUI a1gui, Model m, LinesCanvas canvas)
	{
		this.model = m;
		this.a1gui = a1gui;
		this.canvas = canvas;
	}
	
	/** What to do when the mouse is clicked.*/	
	public void mousePressed(MouseEvent e)
	{
		/** Check if choices still being changed, do nothing. */
		// if choices still being decided
		if (a1gui.choices[0].isEditable() == true)
		{
			return;
		}
		
		/** Check if all Edges have been used, if so, do nothing.*/
		// if all Edges have been used
		if (model.numEdges == 0)
		{
			return;
		}
			
		int xVal = e.getX();
		int firstLine = 0;
		int secondLine = 0;
		
		/** Checks the location of the line, compared to other lines*/
		for (int r = 0; r < model.numLines - 1; r++)
		{
			if (canvas.x[r] <= xVal && xVal <= canvas.x[r+1])
			{
				// should throw a check to model.addEdge here, to check if near another line
				firstLine = r;
				secondLine = r+1;
				
				/** Calls the model to check the line location and if true, creates the edge.
				 * The edge is placed in the correct position of the ArrayList, and the edges left is decremented.
				 */
				if (model.addEdge(firstLine, secondLine, e.getY()))
				{
					Edge edge = new Edge(firstLine, secondLine, e.getY());
					model.sortEdge(edge);
					
					model.numEdges--;
				}
				
				/** Refreshes the canvas no matter what.*/
				canvas.repaint();
				
				/** If the last edge was placed, call the model to print out the choices.*/
				if (model.numEdges == 0)
				{
					model.isDone();
				}
			}
		}
		
		/** checks to see if the edges is not between two lines.*/
		if (xVal <= canvas.x[0])
		{
			System.err.println("Invalid Edge, Out of Bounds");
			return;
		}
		if (xVal >= canvas.x[model.numLines - 1])
		{
			System.err.println("Invalid Edge, Out of Bounds");
			return;
		}
	}


	/** Mouse methods that I did not need, but don't want to get rid of them, in case I will need them.*/
	@Override
	public void mouseClicked(MouseEvent e) {
		// TODO Auto-generated method stub	
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
	}
}